package com.spring.sunflower.anchor

import android.content.Intent
import android.graphics.Color
import android.media.MediaPlayer
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.*
import androidx.appcompat.app.ActionBar
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.flexbox.FlexboxLayout
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lxj.xpopup.XPopup
import com.makeramen.roundedimageview.RoundedImageView
import com.spring.sunflower.R
import com.spring.sunflower.base.BaseActivity
import com.spring.sunflower.bean.AnchorDetailBean
import com.spring.sunflower.bean.AnchorGiftReceivedBean
import com.spring.sunflower.bean.LabelBean
import com.spring.sunflower.common.PhotoViewerActivity
import com.spring.sunflower.common.ReportActivity
import com.spring.sunflower.common.VideoPlayActivity
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.conversation.ChatActivity
import com.spring.sunflower.conversation.ChatVideoActivity
import com.spring.sunflower.dialog.DialogManager
import com.spring.sunflower.dialog.OnPermissionIntroClickListener
import com.spring.sunflower.event.FollowEvent
import com.spring.sunflower.userinfo.PhotoWallActivity
import com.spring.sunflower.userinfo.UserInfoEditActivity
import com.spring.sunflower.util.AppUtils
import com.spring.sunflower.util.AudioUtils
import com.spring.sunflower.util.DisplayUtils
import com.spring.sunflower.util.StatusBarUtil
import com.spring.sunflower.widget.CustomBubbleAttachPopup
import com.spring.sunflower.widget.LineWaveVoiceView
import com.youth.banner.Banner
import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation
import kotlinx.android.synthetic.main.activity_personal_detail.*
import org.greenrobot.eventbus.EventBus
import java.util.*

/**
 * Created by Kevin on 2021/8/8<br/>
 *
 * Describe:<br/>
 */
class PersonalDetailActivity : BaseActivity<AnchorInfoPresenter>(),
    AnchorContract.AnchorInfoView, View.OnClickListener {
    private var banner: Banner<*, *>? = null
    private var tvName: TextView? = null
    private var tvAge: TextView? = null
    private var tvAddress: TextView? = null
    private var tvProfession: TextView? = null
    private var tvID: TextView? = null
    private var tvEmotionState: TextView? = null
    private var tvEducation: TextView? = null
    private var tvHeight: TextView? = null
    private var tvSign: TextView? = null
    private var tvTitle: TextView? = null
    private var tvTime: TextView? = null
    private var nestedScrollView: NestedScrollView? = null
    private val mOffset = 0
    private var mScrollY = 0
    private var toolbar: Toolbar? = null
    private var ivAvatar: RoundedImageView? = null
    private var ivOtherAvatar: RoundedImageView? = null

    private var fblPhoto: FlexboxLayout? = null
    private var fblVideoShow: FlexboxLayout? = null
    private var llContainer: LinearLayout? = null

    //    private  var ivVideoArrow:android.widget.ImageView? = null
    private var actionBar: ActionBar? = null
    private var anchorID: String? = null
    private var tvFunction: TextView? = null
    private var mHasBlacked = false
    private var mHasFollowed = false
    private var mLabelData: MutableList<LabelBean.DatasBean> = ArrayList()
    private var mLabelNameList: MutableList<String> = ArrayList()
    private var tvAccost: TextView? = null
    private var llVideoCall: LinearLayout? =
        null
    private var llMessageChat: LinearLayout? = null

    //    private var llGiftSend: LinearLayout? = null
    private val bannerPlaceHolder: ImageView? = null
    private val mAvatarUrl: String? = null
    private var mSelfAvatar: String = ""
    private var rlVoiceSign: RelativeLayout? = null
    private var photoVOList: MutableList<AnchorDetailBean.DatasBean.PhotoVOListBean> = ArrayList()
    private var tempList: ArrayList<String> = ArrayList()
    private var userID: String = ""
    private var mOtherShowName: String? = null
    private var mOtherFaceUrl: String? = null
    private var voiceWave: LineWaveVoiceView? = null
    private var isVoicePlay = false
    private var voiceSignUrl = ""
    private var audioUtils: AudioUtils? = null
    private var tvStatus: TextView? = null
    private var ivStatus: ImageView? = null
    private var llStatus: LinearLayout? = null
    private var llOtherContainer: LinearLayout? = null
    private var llSelfContainer: LinearLayout? = null
    private var llEditPersonalInfo: LinearLayout? = null
    private var tvPicWall: TextView? = null
    private var isClickEdit = false
    private var rlIntimacyContainer: RelativeLayout? = null
    private var guideVideoDialog: PopupWindow? = null
    private var ivVideo: ImageView? = null
    val r = Runnable {
        guideVideoDialog = DialogManager.getInstance()
            .showGuideVideoDialog(this, llOtherContainer!!)
        startAnim()
        guideVideoDialog?.setOnDismissListener { clearAnim() }
        mHandler.postDelayed(rDismiss, 5000)
    }
    val rDismiss = Runnable {
        //消失
        guideVideoDialog?.let {
            if (it.isShowing) {
                it.dismiss()
            }
        }
    }
    private val mHandler by lazy { Handler(Looper.myLooper()!!) }
    override fun initView() {
        val intent = intent
        anchorID = intent.getStringExtra(Constant.KEY_TARGET_ID)
        userID = getField(Constant.KEY_USERID, "")
        mSelfAvatar = getField(Constant.KEY_PHOTO, "")
        audioUtils = AudioUtils.getInstance()
        toolbar = findViewById(R.id.toolBar)
        tvTitle = findViewById(R.id.tv_title)
        tvFunction = findViewById(R.id.tv_function)
        AppUtils.setFont(this, tvFunction)
        tvStatus = findViewById(R.id.tvStatus)
        ivStatus = findViewById(R.id.vStatus)
        llStatus = findViewById(R.id.llStatus)

        rlIntimacyContainer = findViewById(R.id.likable_level_layout)

        ivAvatar = findViewById(R.id.ivAvatar)
        ivOtherAvatar = findViewById(R.id.ivOtherAvatar)
        voiceWave = findViewById(R.id.voiceWave)
        Glide.with(this)
            .load(mSelfAvatar)
            .placeholder(R.drawable.ic_placeholder)
            .error(R.drawable.ic_placeholder)
            .apply(
                RequestOptions.bitmapTransform(
                    CropCircleWithBorderTransformation(
                        1,
                        Color.parseColor("#FADB4A")
                    )
                )
            )
            .into(ivAvatar!!)
        tvAge = findViewById(R.id.tvAge)
        tvAddress = findViewById(R.id.tvAddress)
        tvID = findViewById(R.id.tvID)
        tvTime = findViewById(R.id.tvTime)
        nestedScrollView = findViewById(R.id.nestedScrollView)
        llContainer = findViewById(R.id.ll_container)
        tvSign = findViewById(R.id.tvSign)
        tvEmotionState = findViewById(R.id.tvEmotionState)
        tvEducation = findViewById(R.id.tvEducation)
        tvHeight = findViewById(R.id.tvHeight)
        fblPhoto = findViewById(R.id.fblPhoto)
        fblVideoShow = findViewById(R.id.fblVideoShow)
        rlVoiceSign = findViewById(R.id.rlVoiceSign)
        tvAccost = findViewById(R.id.tvAccost)
        llVideoCall = findViewById(R.id.llVideoCall)
        llMessageChat = findViewById(R.id.llMesssageChat)
        ivVideo = findViewById(R.id.ivVideo)
        llOtherContainer = findViewById(R.id.llOtherContainer)
        llSelfContainer = findViewById(R.id.llSelfContainer)
        llEditPersonalInfo = findViewById(R.id.llEditPersonalInfo)
        tvPicWall = findViewById(R.id.tvPicWall)

        if (anchorID.equals(userID)) {
            llOtherContainer!!.visibility = View.GONE
            llSelfContainer!!.visibility = View.VISIBLE
            rlIntimacyContainer!!.visibility = View.GONE
            tvFunction!!.visibility = View.INVISIBLE
        } else {
            llOtherContainer!!.visibility = View.VISIBLE
            llSelfContainer!!.visibility = View.GONE
            rlIntimacyContainer!!.visibility = View.VISIBLE
            tvFunction!!.visibility = View.VISIBLE
        }
        mPresenter.getAnchorDetail(anchorID)
        mPresenter.getGiftLogReceived(anchorID, "1")
        mPresenter.getHasBlacked(anchorID, userID)
        mPresenter.getHasFollowed(anchorID)

//        llGiftSend = findViewById(R.id.llGiftSend)
        nestedScrollView?.setOnScrollChangeListener(object :
            NestedScrollView.OnScrollChangeListener {
            var lastScrollY = 0
            var h = DisplayUtils.dip2px(this@PersonalDetailActivity, 170f)
            var color =
                ContextCompat.getColor(applicationContext, R.color.colorPrimary) and 0x00ffffff
            var titleColor =
                ContextCompat.getColor(applicationContext, R.color.white) and 0x00ffffff

            override fun onScrollChange(
                v: NestedScrollView,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                var scrollY = scrollY
                if (lastScrollY < h) {
                    scrollY = Math.min(h, scrollY)
                    mScrollY = if (scrollY > h) h else scrollY
                    //                    buttonBar.setAlpha(1f * mScrollY / h);
                    toolbar?.setBackgroundColor(255 * mScrollY / h shl 24 or color)
                    //                    ivParallax.setTranslationY(mOffset - mScrollY);
//                    tvTitle.setTextColor(255 * mScrollY / h shl 24 or titleColor)
                }
                lastScrollY = scrollY
            }
        })
        toolbar?.setBackgroundColor(0)
//        tvTitle.setTextColor()
        actionBar = supportActionBar
        actionBar?.let {
            it.setDisplayHomeAsUpEnabled(true)
            it.setHomeButtonEnabled(true)
        }
        StatusBarUtil.immersive(this)
        StatusBarUtil.setPaddingSmart(this, toolbar)
        tvFunction!!.setOnClickListener(this)
        tvAccost!!.setOnClickListener(this)
        llVideoCall!!.setOnClickListener(this)
        llMessageChat!!.setOnClickListener(this)
        llEditPersonalInfo?.setOnClickListener(this)
        tvPicWall?.setOnClickListener(this)
//        llGiftSend!!.setOnClickListener(this)
        rlVoiceSign!!.setOnClickListener {
            isVoicePlay = !isVoicePlay
            if (!isVoicePlay) {
                voiceWave!!.startRecord()
                audioUtils!!.play(voiceSignUrl, object : AudioUtils.PlayCallBack {
                    override fun onCompletion(param1MediaPlayer: MediaPlayer?) {
                        voiceWave!!.stopRecord()
                    }

                    override fun onPrepared(param1MediaPlayer: MediaPlayer?) {
                    }

                })
            } else {
                voiceWave!!.stopRecord()
                audioUtils!!.stopPlay()
            }
        }
    }

    override fun getLayoutID(): Int = R.layout.activity_personal_detail

    override fun setPresenter(): AnchorInfoPresenter = AnchorInfoPresenter(this)
    override fun onResume() {
        super.onResume()
        if (anchorID.equals(userID) && isClickEdit) {
            mPresenter.getAnchorDetail(anchorID)
            mPresenter.getGiftLogReceived(anchorID, "1")
            mPresenter.getHasBlacked(anchorID, userID)
            mPresenter.getHasFollowed(anchorID)
            isClickEdit = false
        }
    }

    override fun showAnchorData(data: AnchorDetailBean.DatasBean?) {
        photoVOList = data!!.photoVOList
        tempList.clear()
        fblPhoto?.removeAllViews()
        fblVideoShow?.removeAllViews()
        if (photoVOList.size > 5) {
            for (d in 0 until 5) {
                tempList.add(photoVOList[d].photoPath)
                val generatePhoto = generatePhoto(photoVOList[d].photoPath, d, true)
                fblPhoto?.addView(generatePhoto)
            }
        } else if (photoVOList.size > 0) {
            for (d in 0 until photoVOList.size) {
                tempList.add(photoVOList[d].photoPath)
                val generatePhoto = generatePhoto(photoVOList[d].photoPath, d, false)
                fblPhoto?.addView(generatePhoto)
            }
        } else {
            if (data!!.photo == null) return
            tempList.add(data.photo)
            val generatePhoto = generatePhoto(data.photo, 0, false)
            fblPhoto?.addView(generatePhoto)
        }
        val onlineMoodV = data.onlineMoodV
        if (data.status.equals("4")) {
            if (!anchorID.equals(userID)) {
                mHandler.postDelayed(r, 3000)
            }
            if (onlineMoodV != null && onlineMoodV.size > 0) {//4的在线 0显示多少分钟前在线
                llStatus?.visibility = View.VISIBLE
                ivStatus?.visibility = View.VISIBLE
                val name = onlineMoodV[0].name
                val id = onlineMoodV[0].id
                tvStatus!!.text = name
//                when (id) {
//                    "2846" -> {
//                        vStatus?.setBackgroundResource(R.drawable.bg_status_green)
//                    }
//                    "2847" -> {
//                        vStatus?.setBackgroundResource(R.drawable.bg_status_green)
//                    }
//                    "2848" -> {
//                        vStatus?.setBackgroundResource(R.drawable.bg_status_red)
//                    }
//                }
            } else {
                llStatus?.visibility = View.INVISIBLE
            }
        } else if (data.status.equals("0")) {//是不在线
            llStatus?.visibility = View.VISIBLE
            ivStatus?.visibility = View.GONE
            tvStatus!!.text = data.lastOnLineTimeDesc

        }
        tvAge!!.text = if (data!!.age == "0") "年龄：保密" else "年龄：${data!!.age}岁"
        tvTitle.text = data.nickname
        mOtherShowName = data.nickname
        mOtherFaceUrl = data.photo
        tvID!!.text = "ID：" + data.id
        tvAddress!!.text = data.city
        tvHeight!!.text = if (data.height == "0") "身高：保密" else "身高：${data.height}cm"
        val educationV = data.educationV
        tvEducation!!.text = if (educationV.size > 0) "学历：${educationV[0].name}" else "学历：保密"
        tvSign!!.text = data.signature
        Glide.with(this)
            .load(data.photo)
            .placeholder(R.drawable.ic_placeholder)
            .error(R.drawable.ic_placeholder)
            .apply(
                RequestOptions.bitmapTransform(
                    CropCircleWithBorderTransformation(
                        1,
                        Color.parseColor("#FADB4A")
                    )
                )
            )
            .into(ivOtherAvatar!!)
        if (!TextUtils.isEmpty(data.voiceSignature)) {
            voiceSignUrl = data.voiceSignature
            rlVoiceSign!!.visibility = View.VISIBLE
            tvTime?.text = "${data.voiceSignatureDuration}''"
        } else {
            rlVoiceSign!!.visibility = View.INVISIBLE
        }
        val videoDetailVOList = data.videoDetailVOList
        if (videoDetailVOList.size > 0) {
            Collections.reverse(videoDetailVOList)
            if (videoDetailVOList.size > 4) {
                for (i in 0..3) {
                    val videoDetailVOListBean = videoDetailVOList[i]
                    val videoFirstPhotoUrl = videoDetailVOListBean.videoFirstPhotoUrl
                    val videoPath = videoDetailVOListBean.videoPath
                    val view: View = generateVideoShow(videoFirstPhotoUrl, videoPath, i, true)
                    fblVideoShow!!.addView(view)
                }
            } else {
                for (d in 0 until videoDetailVOList.size) {
                    val videoFirstPhotoUrl = videoDetailVOList[d].videoFirstPhotoUrl
                    val videoPath = videoDetailVOList[d].videoPath
                    val view: View = generateVideoShow(videoFirstPhotoUrl, videoPath, d, false)
                    fblVideoShow!!.addView(view)
                }
            }
        }
    }

    override fun showGiftReceived(data: MutableList<AnchorGiftReceivedBean.DatasBean>?) {
    }

    override fun hasFollowed(hasFollowed: Boolean) {
        mHasFollowed = hasFollowed
    }

    override fun setFollowedSuccess() {
        mHasFollowed = !mHasFollowed
        showToast(if (mHasFollowed) "已关注" else "已取消")
        val event = FollowEvent()
        event.isHasFollowed = mHasFollowed
        event.userID = anchorID
        EventBus.getDefault().post(event)
    }

    override fun setFollowedFailed() {
    }

    override fun hasBlacked(hasBlacked: Boolean) {
        mHasBlacked = hasBlacked
    }

    override fun blackAddSuccess() {
        mHasBlacked = true
        showToast("已拉黑")
    }

    override fun blackAddFailed() {
        mHasBlacked = false
        showToast("拉黑失败")
    }

    override fun blackRemoveSuccess() {
        mHasBlacked = true
        showToast("已解除")
    }

    override fun blackRemoveFailed() {
        mHasBlacked = false
        showToast("解除失败")
    }

    override fun showReportType(data: List<LabelBean.DatasBean>) {
        mLabelData = data.toMutableList()
        mLabelNameList.clear()
        for (d in data) {
            val name = d.name
            mLabelNameList.add(name)
        }
        val stringArr = mLabelNameList.toTypedArray()
        XPopup.Builder(this)
            .hasShadowBg(true)
            .asBottomList(
                null, stringArr
            ) { position, text ->
                val intent = Intent(this, ReportActivity::class.java)
                intent.putExtra(Constant.KEY_REPORT_TYPE, data[position].id)
                intent.putExtra("reportName", text)
                intent.putExtra("otherID", anchorID)
                startActivity(intent)
            }
            .show()
    }

    override fun liveApplySuccess() {
        val intent = Intent(this, ChatVideoActivity::class.java)
        intent.putExtra(Constant.VIDEO_CALL_SELF_DIAL, true)
        intent.putExtra(Constant.VIDEO_CALL_OTHER_ID, anchorID)
        intent.putExtra(Constant.VIDEO_CALL_OTHER_FACE_URL, mOtherFaceUrl)
        intent.putExtra(Constant.VIDEO_CALL_OTHER_NICKNAME, mOtherShowName)
        startActivity(intent)
    }

    override fun sayHelloSuccess() {
        showToast("搭讪成功")
    }

    override fun sayHelloFailed(msg: String) {
        showToast(msg)
    }

    private fun generatePhoto(photoPath: String, index: Int, isMax4: Boolean): View {
        val view: RelativeLayout =
            LayoutInflater.from(this)
                .inflate(R.layout.layout_personal_photo, null) as RelativeLayout
        val ivCover: RoundedImageView = view.findViewById(R.id.ivCover)
        val tvTip: TextView = view.findViewById(R.id.tvTip)

        val layoutParams = ViewGroup.LayoutParams(-2, -2)
        val screenWidth = DisplayUtils.getScreenWidth(this)
        val i = DisplayUtils.dip2px(this, 30f)
        val bigSize = DisplayUtils.dip2px(this, 100f)
        val container = view.findViewById<RelativeLayout>(R.id.rl_container)
        if (index == 0) {
            layoutParams.width = bigSize
            view.layoutParams = layoutParams
            view.gravity = Gravity.CENTER
            val params = ivCover.layoutParams
            params.width = bigSize - DisplayUtils.dpTpx(this, 6)
            params.height = bigSize - DisplayUtils.dpTpx(this, 6)
            ivCover.layoutParams = params
            container.setOnClickListener {
                val intent = Intent(this, PhotoViewerActivity::class.java)
                intent.putStringArrayListExtra(Constant.PHOTO_LIST_VIEWER, tempList);
                intent.putExtra(Constant.PHOTO_CURRENT_POSITION, index);
                startActivity(intent)
            }
        } else {
            val itemWidth = (screenWidth - bigSize - i) / 4
            layoutParams.width = itemWidth
            view.layoutParams = layoutParams
            view.gravity = Gravity.CENTER
            val params = ivCover.layoutParams
            params.width = itemWidth - DisplayUtils.dpTpx(this, 6)
            params.height = itemWidth - DisplayUtils.dpTpx(this, 6)
//            params.height = itemWidth - DisplayUtils.dpTpx(this, 5)
            ivCover.layoutParams = params
            if (isMax4 && index == 4) {
                tvTip.visibility = View.VISIBLE
                tvTip.layoutParams = params
                tvTip.setBackgroundResource(R.drawable.bg_black_alpha_corner_5)
                tvTip.setText("查看更多")
                container.setOnClickListener {
                    val intent = Intent(this, PhotoListActivity::class.java)
                    intent.putExtra("otherId", anchorID)
                    startActivity(intent)
                }
            } else {
                tvTip.visibility = View.GONE
                container.setOnClickListener {
                    val intent = Intent(this, PhotoViewerActivity::class.java)
                    intent.putStringArrayListExtra(Constant.PHOTO_LIST_VIEWER, tempList);
                    intent.putExtra(Constant.PHOTO_CURRENT_POSITION, index);
                    startActivity(intent)
                }

            }


        }
        Glide.with(this)
            .load(photoPath)
            .placeholder(R.drawable.ic_placeholder)
            .error(R.drawable.ic_placeholder)
            .into(ivCover)
        return view
    }

    private fun generateVideoShow(
        path: String?,
        videoPath: String?,
        index: Int,
        isMax3: Boolean
    ): View {
        val view = LayoutInflater.from(this).inflate(R.layout.layout_video_show, null)
        val tvVideo = view.findViewById<TextView>(R.id.tvVideoPlay)
        AppUtils.setFont(this, tvVideo)
        val ivVideoShow: RoundedImageView = view.findViewById(R.id.ivVideoCover)
        val tvTip: TextView = view.findViewById(R.id.tvTip)
        val layoutParams = RelativeLayout.LayoutParams(-2, -2)
        val screenWidth = DisplayUtils.getScreenWidth(this)
        val i = DisplayUtils.dip2px(this, 60f)
        val giftWidth = (screenWidth - i) / 4
        layoutParams.width = giftWidth
        layoutParams.height = giftWidth
        if (index > 0) {
            layoutParams.leftMargin = DisplayUtils.dip2px(this, 10f)
        }
        view.layoutParams = layoutParams
        val params = RelativeLayout.LayoutParams(-2, -2)
        params.width = giftWidth
        params.height = giftWidth
        ivVideoShow.layoutParams = params
        Glide.with(this)
            .load(if (TextUtils.isEmpty(path)) videoPath else path)
            .placeholder(R.drawable.ic_placeholder)
            .error(R.drawable.ic_placeholder)
            .into(ivVideoShow)
        val container = view.findViewById<RelativeLayout>(R.id.rl_container)
        if (isMax3 && index == 2) {
            tvVideo.visibility = View.GONE
            tvTip.visibility = View.VISIBLE
            tvTip.layoutParams = params
            tvTip.setBackgroundResource(R.drawable.bg_black_alpha_corner_5)
            tvTip.setText("查看更多")
            container.setOnClickListener {
                val intent = Intent(this, VideoShowActivity::class.java)
//                intent.putExtra(Constant.KEY_VIDEO_URL, videoPath)
                intent.putExtra("otherId", anchorID)
                startActivity(intent)
            }

        } else {
            tvVideo.visibility = View.VISIBLE
            tvTip.visibility = View.GONE
            container.setOnClickListener {
                val intent = Intent(this, VideoPlayActivity::class.java)
                intent.putExtra(Constant.KEY_VIDEO_URL, videoPath)
                intent.putExtra("currentIndex", index)
                intent.putExtra("otherId", anchorID)
                startActivity(intent)
            }
        }
        return view
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.ivVideoArrow -> {
            }
            R.id.ivGiftArrow -> {
                val intent = Intent(this, GiftReceivedActivity::class.java)
                intent.putExtra(Constant.KEY_ANCHOR_ID, anchorID)
                startActivity(intent)
            }
            R.id.tv_function -> XPopup.Builder(this)
                .atView(tvFunction)
                .hasShadowBg(false)
                .asCustom(CustomBubbleAttachPopup(
                    this, mHasBlacked, mHasFollowed
                ) { position, text -> handlePopupAction(position) })
                .show()
            R.id.tvAccost -> {
                mPresenter.sayHello(anchorID, userID)
            }
            R.id.llVideoCall -> {
                if (!XXPermissions.isGranted(
                        this,
                        Permission.RECORD_AUDIO
                    ) || !XXPermissions.isGranted(this, Permission.CAMERA)
                ) {
                    showPermissionIntroDialog(
                        arrayOf(
                            getString(R.string.permission_audio_title),
                            getString(R.string.permission_camera_title)
                        ),
                        arrayOf(
                            getString(R.string.permission_audio_desc),
                            getString(R.string.permission_camera_desc)
                        ),
                        object : OnPermissionIntroClickListener {
                            override fun onClickOK() {
                                XXPermissions.with(this@PersonalDetailActivity)
                                    .permission(Permission.RECORD_AUDIO, Permission.CAMERA)
                                    .request(object : OnPermissionCallback {
                                        override fun onGranted(
                                            permissions: List<String>,
                                            all: Boolean
                                        ) {
                                            if (all) {
                                                saveField(Constant.KEY_USERID_CHATTER, anchorID)
                                                saveField(
                                                    Constant.KEY_AVATAR_CHATTER,
                                                    mOtherFaceUrl
                                                )
                                                saveField(
                                                    Constant.KEY_NICKNAME_CHATTER,
                                                    mOtherShowName
                                                )
                                                mPresenter.applyChat(
                                                    userID,
                                                    anchorID
                                                )
                                                mGrantedCameraPermission = true
                                                mGratedRecordPermission = true
                                            } else {
                                                showPermissionIntroDialog(
                                                    getString(R.string.permission_denied_title),
                                                    "无法正常进行视频通话",
                                                    null
                                                )
                                            }
                                        }

                                        override fun onDenied(
                                            permissions: List<String>,
                                            never: Boolean
                                        ) {
                                            showPermissionIntroDialog(
                                                getString(R.string.permission_denied_title),
                                                "无法正常进行视频通话",
                                                null
                                            )
                                        }
                                    })
                            }

                            override fun onClickCancel() {}
                        })
                } else {
                    saveField(Constant.KEY_USERID_CHATTER, anchorID)
                    saveField(
                        Constant.KEY_AVATAR_CHATTER,
                        mOtherFaceUrl
                    )
                    saveField(Constant.KEY_NICKNAME_CHATTER, mOtherShowName)
                    mPresenter.applyChat(userID, anchorID)
                }
            }
            R.id.llMesssageChat -> goMessageChat()
            R.id.llGiftSend -> {
            }
            R.id.llEditPersonalInfo -> {
                isClickEdit = true
                startNewActivity(UserInfoEditActivity::class.java)
            }
            R.id.tvPicWall -> {
                startNewActivity(PhotoWallActivity::class.java)
            }
        }
    }

    private fun goMessageChat() {
        val intent = Intent(this, ChatActivity::class.java)
        intent.putExtra(Constant.C2C_CONVERSATION_ID, "")
        intent.putExtra(Constant.C2C_USER_ID, anchorID)
        intent.putExtra(Constant.C2C_SHOW_NAME, tvTitle!!.text.toString())
        intent.putExtra(Constant.C2C_FACE_URL, mOtherFaceUrl)
        intent.putExtra(Constant.C2C_DRAFT_TEXT, "")
        startActivity(intent)
    }

    private fun handlePopupAction(position: Int) {
        val isSelf = if (anchorID.equals(userID)) true else false
        when (position) {
            0 -> {
                if (isSelf) {
                    showToast("不能关注自己")
                    return
                }
                mPresenter.setFollowed(anchorID, if (mHasFollowed) "0" else "1")
            }
            1 -> {
                if (isSelf) {
                    showToast("不能拉黑自己")
                    return
                }
                if (mHasBlacked) {
                    mPresenter.blackRemove(anchorID)
                } else {
                    mPresenter.blackAdd(anchorID)
                }
            }

            2 -> {
                if (isSelf) {
                    showToast("不能举报自己")
                    return
                }
                mPresenter.getReportType()
            }
            3 -> showToast("该功能待开放...")
        }
    }

    fun startAnim() {
        val animation = TranslateAnimation(
            Animation.RELATIVE_TO_SELF, -0.1f, Animation.RELATIVE_TO_SELF, 0.1f,
            Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f
        )
        animation.duration = 100
        animation.repeatMode = Animation.REVERSE
        animation.repeatCount = 100
//        animation.start()
        ivVideo?.startAnimation(animation)
    }

    private fun clearAnim() {
        ivVideo?.let {
            val animation = it.animation
            animation
            animation?.cancel()
            it.clearAnimation()
        }
    }

    override fun onStop() {
        super.onStop()
        audioUtils?.let {
            if (it.isPlay) {
                voiceWave?.stopRecord()
                it.stopPlay()
            }
        }
        guideVideoDialog?.let {
            if (it.isShowing) it.dismiss()
        }
        clearAnim()
        mHandler.removeCallbacks(r)
        mHandler.removeCallbacks(rDismiss)
    }
}